<template>
  <div v-if="branch" class="bg-white p-6 rounded-lg flex flex-col h-full">

    <div class="flex items-center border-b border-gray-200 pb-4 mb-4">
      <n-button circle strong secondary @click="goBackToList" class="mr-4">
        <template #icon><n-icon><arrow-back-outline /></n-icon></template>
      </n-button>
      <n-divider vertical class="!h-8" />
      <span class="text-xl font-semibold ml-4">{{ branch.branchName || '党支部详情' }}</span>
      <n-space align="center" class="ml-auto">
        <n-button type="error" @click="handleDeleteBranch">
            <template #icon><n-icon><trash-outline /></n-icon></template>
            删除党支部
        </n-button>
      </n-space>
    </div>

    <div class="flex flex-1 min-h-0">
      <div class="w-64 flex-shrink-0 flex flex-col border-r border-gray-200 pr-4">
        <div class="flex-1 overflow-y-auto">
          <div class="space-y-2 p-2">
            <div 
              v-for="item in subMenuList" 
              :key="item.key" 
              @click="activeTabKey = item.key"
              :class="[
                'flex items-center p-3 rounded-lg cursor-pointer transition-all duration-200',
                activeTabKey === item.key
                  ? 'bg-blue-50 border-2 border-blue-200 text-blue-700'
                  : 'bg-gray-50 border-2 border-transparent hover:bg-gray-100 text-gray-700'
              ]">
                <span class="text-sm font-medium">{{ item.label }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="flex-1 pl-6 overflow-y-auto">
        <div v-if="activeItem" class="h-full">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-lg font-semibold text-gray-800">{{ activeItem.label }}</h2>
            <div v-if="activeItem.key === 'basicInfo'">
               <n-button type="primary" @click="handleEditBasicInfo">
                 <template #icon><n-icon><create-outline /></n-icon></template>
                 编辑信息
               </n-button>
            </div>
            <div v-else-if="activeItem.key === 'committee'">
               <n-button type="info" @click="handleEndCommitteeTerm" :disabled="!currentCommittee">
                 <template #icon><n-icon><time-outline /></n-icon></template>
                 结束任期
               </n-button>
               <n-button type="primary" @click="handleCommitteeTransition" class="ml-2">
                 <template #icon><n-icon><swap-horizontal-outline /></n-icon></template>
                 支委换届
               </n-button>
            </div>
            <n-space v-else-if="activeItem.key === 'activity'">
               <n-button type="primary" @click="handleAddActivity">
                 <template #icon><n-icon><add-outline /></n-icon></template>
                 新增活动
               </n-button>
            </n-space>
          </div>

          <component
            :is="activeItem.displayComponent"
            :branch="branch"
            :branch-data="branch"
            :activities="branch.branchActivities || []"
            :committees="branch.branchCommittees || []"
            :current-members="membersWithDetails"
            @edit-committee="data => handleCommitteeEditHistorical(activeItem, data)"
            @delete-committee="data => handleDelete('committee', data)"
            @edit-activity="data => handleActivityEdit(activeItem, data)"
            @delete-activity="data => handleDelete('activity', data)"
            @data-updated="emit('data-updated')"
          />
        </div>
      </div>
    </div>

    <n-drawer v-model:show="isDrawerActive" :width="800" placement="right">
      <n-drawer-content :title="drawerTitle" closable>
        <component
          v-if="editingItem && editingItem.editComponent"
          :is="editingItem.editComponent"
          ref="editorRef"
          :mode="editMode"
          :initial-data="editingData"
          :branch-data="branch"
          @auto-save="handleAutoSave"
        />
        <template #footer>
          <n-space justify="end">
            <n-button @click="isDrawerActive = false">取消</n-button>
            <n-button
              v-if="editMode !== 'edit' || editingItem.key !== 'basicInfo'"
              type="primary"
              :loading="isSaving"
              @click="handleSave"
            >
              保存
            </n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>
  </div>
  
  <div v-else class="flex items-center justify-center h-full">
    <n-spin size="large" />
  </div>
</template>

<script setup>
// 【修改点 2】: 导入 watch 和 useRouter, onMounted
import { ref, computed, defineAsyncComponent, h, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import {
  NSpace, NButton, NIcon, NDivider, NInput,
  NDrawer, NDrawerContent, useMessage, useDialog, NSpin, NDatePicker
} from 'naive-ui';
import {
  ArrowBackOutline, TrashOutline, CreateOutline, AddOutline, SwapHorizontalOutline, TimeOutline
} from '@vicons/ionicons5';

// 导入API接口
import {
  getBranchById,
  deleteBranch,
  updateBranch,
  createCommittee,
  updateCommittee,
  committeeTransition,
  createActivity,
  updateActivity
} from '@/api/branch.js';
import { getAllMembers } from '@/api/member.js';
import { formatDate } from '@/utils/dateUtils.js';

// 组件导入 (保持不变)
import BasicInfoDisplay from './basic/BasicInfoDisplay.vue';
import ActivityDisplay from './basic/ActivityDisplay.vue';
import CommitteeDisplay from './basic/CommitteeDisplay.vue';
import MemberManagement from './members/MemberManagement.vue';
const BasicInfoEditor = defineAsyncComponent(() => import('./basic/BasicInfoEditor.vue'));
const ActivityEditor = defineAsyncComponent(() => import('./basic/ActivityEditor.vue'));
const CommitteeEditor = defineAsyncComponent(() => import('./basic/CommitteeEditor.vue'));


// 【修改点 3】: 修改 Props 定义, 只接收来自路由的 id
const props = defineProps({
  id: {
    type: [String, Number],
    required: true
  }
});

// 【修改点 4】: 修改 Emits 定义, 移除 'back-to-list'
const emit = defineEmits(['data-updated']);

// 【修改点 5】: 获取 router 实例
const router = useRouter();

const message = useMessage();
const dialog = useDialog();

// 【修改点 6】: 新增本地状态来存储组件所需的数据
const branch = ref(null);
const allMembers = ref([]);
const isLoading = ref(true);

// 菜单列表 (保持不变)
const subMenuList = [
  { key: 'basicInfo', label: '基本信息', displayComponent: BasicInfoDisplay, editComponent: BasicInfoEditor },
  { key: 'committee', label: '支委信息', displayComponent: CommitteeDisplay, editComponent: CommitteeEditor },
  { key: 'activity', label: '活动记录', displayComponent: ActivityDisplay, editComponent: ActivityEditor },
  { key: 'members', label: '党员管理', displayComponent: MemberManagement }
];

// 内部 tab 状态 (保持不变)
const activeTabKey = ref(subMenuList[0]?.key || '');
const activeItem = computed(() => 
  subMenuList.find(item => item.key === activeTabKey.value)
);

// 【修改点 7】: 新增数据获取逻辑
const fetchData = async () => {
  isLoading.value = true;
  console.log(`正在加载 ID 为 ${props.id} 的支部详情...`);
  
  // 使用测试数据，不依赖后端API
  try {
    // 创建测试党员数据
    const mockMembers = [
      {
        memberId: 'M001',
        memberName: '张三',
        studentId: '2021001',
        class: '计算机科学与技术1班',
        politicalStatus: '正式党员',
        enrollmentStatus: '在读',
        phoneNumber: '13800138001',
        joinPartyDate: '2021-05-20',
        email: 'zhangsan@example.com',
        gender: '男',
        birthDate: '2000-03-15',
        nation: '汉族',
        joinDate: '2021-09-01' // 加入党支部的日期
      },
      {
        memberId: 'M002',
        memberName: '李四',
        studentId: '2021002',
        class: '计算机科学与技术2班',
        politicalStatus: '正式党员',
        enrollmentStatus: '在读',
        phoneNumber: '13800138002',
        joinPartyDate: '2021-06-15',
        email: 'lisi@example.com',
        gender: '女',
        birthDate: '2000-07-22',
        nation: '汉族',
        joinDate: '2021-09-01'
      },
      {
        memberId: 'M003',
        memberName: '王五',
        studentId: '2021003',
        class: '软件工程1班',
        politicalStatus: '预备党员',
        enrollmentStatus: '在读',
        phoneNumber: '13800138003',
        joinPartyDate: '2022-03-10',
        email: 'wangwu@example.com',
        gender: '男',
        birthDate: '2001-01-08',
        nation: '回族',
        joinDate: '2022-03-01'
      },
      {
        memberId: 'M004',
        memberName: '赵六',
        studentId: '2021004',
        class: '软件工程2班',
        politicalStatus: '正式党员',
        enrollmentStatus: '在读',
        phoneNumber: '13800138004',
        joinPartyDate: '2021-11-25',
        email: 'zhaoliu@example.com',
        gender: '男',
        birthDate: '2000-11-30',
        nation: '汉族',
        joinDate: '2021-09-01'
      },
      {
        memberId: 'M005',
        memberName: '钱七',
        studentId: '2021005',
        class: '信息安全1班',
        politicalStatus: '预备党员',
        enrollmentStatus: '在读',
        phoneNumber: '13800138005',
        joinPartyDate: '2022-09-18',
        email: 'qianqi@example.com',
        gender: '女',
        birthDate: '2001-05-12',
        nation: '汉族',
        joinDate: '2022-09-01'
      },
      {
        memberId: 'M006',
        memberName: '孙八',
        studentId: '2021006',
        class: '信息安全2班',
        politicalStatus: '入党积极分子',
        enrollmentStatus: '在读',
        phoneNumber: '13800138006',
        joinPartyDate: null,
        email: 'sunba@example.com',
        gender: '男',
        birthDate: '2001-08-20',
        nation: '汉族',
        joinDate: '2023-03-01'
      },
      {
        memberId: 'M007',
        memberName: '周九',
        studentId: '2021007',
        class: '网络工程1班',
        politicalStatus: '入党积极分子',
        enrollmentStatus: '在读',
        phoneNumber: '13800138007',
        joinPartyDate: null,
        email: 'zhoujiu@example.com',
        gender: '女',
        birthDate: '2001-11-05',
        nation: '汉族',
        joinDate: '2023-05-01'
      }
    ];
    
    // 创建测试支部数据
    const mockBranchData = {
      branchId: props.id,
      branchName: `计算机学院第${props.id}党支部`,
      establishmentDate: '2020-09-01',
      branchType: '学生党支部',
      affiliation: '计算机学院党委',
      branchSecretary: '张三',
      contactPhone: '010-12345678',
      officeLocation: '计算机楼A301',
      branchDescription: '这是一个充满活力的学生党支部，致力于培养优秀的计算机专业党员。',
      currentMembers: [ // 修改为对象数组，包含状态字段
        { memberId: 'M001', status: '正式党员' },
        { memberId: 'M002', status: '正式党员' },
        { memberId: 'M003', status: '预备党员' },
        { memberId: 'M004', status: '正式党员' },
        { memberId: 'M005', status: '预备党员' },
        { memberId: 'M006', status: '入党积极分子' },
        { memberId: 'M007', status: '入党积极分子' }
      ],
      branchActivities: [
        {
          activityId: 'A001',
          activityName: '学习贯彻党的二十大精神专题会议',
          activityType: '政治学习',
          activityDate: '2023-10-15',
          activityLocation: '计算机楼B201',
          participants: ['M001', 'M002', 'M003', 'M004', 'M005'], // 修改为参与者ID数组
          organizer: '张三',
          activityContent: '本次会议深入学习了党的二十大精神，全体党员积极参与讨论，反响热烈。',
          photos: ['photo1.jpg', 'photo2.jpg']
        },
        {
          activityId: 'A002',
          activityName: '红色教育基地参观活动',
          activityType: '实践活动',
          activityDate: '2023-11-20',
          activityLocation: '北京革命历史博物馆',
          participants: ['M001', 'M002', 'M004'],
          organizer: '李四',
          activityContent: '通过参观红色教育基地，党员们更加深刻地理解了革命历史，增强了党性修养。',
          photos: ['photo3.jpg']
        },
        {
          activityId: 'A003',
          activityName: '志愿服务活动',
          activityType: '志愿服务',
          activityDate: '2023-12-05',
          activityLocation: '社区服务中心',
          participants: ['M002', 'M003', 'M005'],
          organizer: '王五',
          activityContent: '党员们积极参与社区志愿服务，为社区居民提供计算机技术支持，受到好评。',
          photos: ['photo4.jpg', 'photo5.jpg']
        },
        {
          activityId: 'A004',
          activityName: '主题党日活动',
          activityType: '主题党日',
          activityDate: '2024-01-10',
          activityLocation: '学院报告厅',
          participants: ['M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007'],
          organizer: '张三',
          activityContent: '开展"不忘初心，牢记使命"主题党日活动，重温入党誓词，坚定理想信念。',
          photos: ['photo6.jpg']
        }
      ],
      branchCommittees: [
        {
          committeeId: 'C001',
          startDate: '2023-09-01',
          endDate: null, // 表示当前任期未结束
          committeeMembers: [
            {
              memberId: 'M001',
              memberName: '张三',
              positionHeld: '支部书记',
              appointmentDate: '2023-09-01'
            },
            {
              memberId: 'M002',
              memberName: '李四',
              positionHeld: '副书记',
              appointmentDate: '2023-09-01'
            },
            {
              memberId: 'M004',
              memberName: '赵六',
              positionHeld: '组织委员',
              appointmentDate: '2023-09-01'
            }
          ]
        },
        {
          committeeId: 'C002',
          startDate: '2022-09-01',
          endDate: '2023-08-31', // 表示上一任期已结束
          committeeMembers: [
            {
              memberId: 'M001',
              memberName: '张三',
              positionHeld: '副书记',
              appointmentDate: '2022-09-01'
            },
            {
              memberId: 'M004',
              memberName: '赵六',
              positionHeld: '支部书记',
              appointmentDate: '2022-09-01'
            }
          ]
        }
      ]
    };
    
    // 设置数据
    branch.value = mockBranchData;
    allMembers.value = mockMembers;

  } catch (error) {
    message.error("加载数据失败！");
    console.error(error);
  } finally {
    isLoading.value = false;
  }
};

// 【修改点 8】: 新增返回列表的本地方法
const goBackToList = () => {
  router.push({ name: 'branch-list' }); // 假设列表页的路由名称是 'branch-list'
};

// --- 以下所有原有的 script 逻辑基本保持不变, 只是数据源从 props 变为本地的 ref ---

const membersWithDetails = computed(() => {
  // 注意: 数据源从 props.branch 变为 branch.value
  const memberData = branch.value?.currentMembers || [];
  if (!memberData.length || !allMembers.value.length) {
    return [];
  }
  
  // 处理两种情况：如果是ID数组，转换为对象数组
  if (typeof memberData[0] === 'string') {
    // 旧格式：ID数组
    const memberMap = new Map(allMembers.value.map(m => [m.memberId, m]));
    return memberData
      .map(id => memberMap.get(id))
      .filter(Boolean);
  } else {
    // 新格式：对象数组，包含status字段
    const memberMap = new Map(allMembers.value.map(m => [m.memberId, m]));
    return memberData
      .map(item => {
        const member = memberMap.get(item.memberId);
        if (member) {
          // 合并成员信息和状态
          return { ...member, status: item.status };
        }
        return null;
      })
      .filter(Boolean);
  }
});

// 抽屉、保存、删除等逻辑保持不变, 它们会自动使用最新的本地 ref 数据
const isDrawerActive = ref(false);
const editorRef = ref(null);
const isSaving = ref(false);
const editingItem = ref(null);
const editMode = ref('edit');
const editingData = ref(null);

const drawerTitle = computed(() => {
  if (!editingItem.value) return '';
  const modeText = { add: '新增', edit: '编辑', transition: '换届' };
  return `${modeText[editMode.value] || '编辑'} - ${editingItem.value.label}`;
});

const openDrawer = (item, mode, data = null) => {
  editingItem.value = item;
  editMode.value = mode;
  editingData.value = data;
  isDrawerActive.value = true;
};

const currentCommittee = computed(() => {
  if (!branch.value || !branch.value.branchCommittees) return null;
  return branch.value.branchCommittees.find(c => !c.endDate);
});

// 处理编辑基本信息
const handleEditBasicInfo = () => {
  const basicInfoItem = subMenuList.find(item => item.key === 'basicInfo');
  openDrawer(basicInfoItem, 'edit', branch.value);
};

// 处理结束支委任期
const handleEndCommitteeTerm = () => {
  if (!currentCommittee.value) return;
  
  // 打开一个对话框，让用户选择结束日期
  const endDateRef = ref(null);
  const endDateValue = ref(null);
  
  dialog.create({
    title: '结束支委任期',
    content: () => h('div', { class: 'p-4' }, [
      h('p', { class: 'mb-4' }, '请选择当前支委任期的结束日期：'),
      h('div', { class: 'mb-2' }, [
        h('span', { class: 'text-sm text-gray-600' }, '当前支委开始日期：'),
        h('span', { class: 'text-sm font-medium ml-2' }, formatDate(currentCommittee.value.startDate))
      ]),
      h(NDatePicker, {
        ref: endDateRef,
        value: endDateValue.value,
        'onUpdate:value': (value) => { endDateValue.value = value; },
        type: 'date',
        valueFormat: 'yyyy-MM-dd',
        class: 'w-full',
        placeholder: '请选择结束日期'
      })
    ]),
    positiveText: '确认结束',
    negativeText: '取消',
    onPositiveClick: async () => {
      if (!endDateValue.value) {
        message.warning('请选择结束日期');
        return false; // 阻止对话框关闭
      }
      
      try {
        const updateData = {
          committeeId: currentCommittee.value.committeeId,
          endDate: endDateValue.value
        };
        
        await updateCommittee(props.id, currentCommittee.value.committeeId, updateData);
        message.success('支委任期已结束');
        await fetchData();
        emit('data-updated');
      } catch (error) {
        console.error('结束支委任期失败:', error);
        message.error('操作失败，请重试');
        return false; // 阻止对话框关闭
      }
    }
  });
};

// 处理支委换届
const handleCommitteeTransition = () => {
  const committeeItem = subMenuList.find(item => item.key === 'committee');
  openDrawer(committeeItem, 'transition', currentCommittee.value);
};

// 处理新增活动
const handleAddActivity = () => {
  const activityItem = subMenuList.find(item => item.key === 'activity');
  openDrawer(activityItem, 'add', null);
};

// 处理自动保存（主要用于基本信息编辑）
const handleAutoSave = async (data) => {
  try {
    if (editingItem.value && editingItem.value.key === 'basicInfo') {
      await updateBranch(props.id, data);
      // 更新本地数据
      Object.assign(branch.value, data);
      message.success('基本信息已自动保存', { duration: 2000 });
      emit('data-updated');
    }
  } catch (error) {
    console.error('自动保存失败:', error);
    message.error('自动保存失败，请重试');
  }
};

// 处理保存
const handleSave = async () => {
  if (!editorRef.value || !editingItem.value) return;
  
  try {
    isSaving.value = true;
    const result = await editorRef.value.validateAndGetData();
    
    if (!result) {
      message.error('请检查表单填写是否正确');
      return;
    }
    
    // 根据不同的编辑类型调用不同的API
    if (editingItem.value.key === 'committee') {
      // 处理支委相关操作
      if (result.mode === 'add') {
        await createCommittee(props.id, result.data);
        message.success('支委信息添加成功');
      } else if (result.mode === 'edit') {
        await updateCommittee(props.id, result.data.committeeId, result.data);
        message.success('支委信息更新成功');
      } else if (result.mode === 'transition') {
        await committeeTransition(props.id, result.data);
        message.success('支委换届成功');
      }
      // 重新获取数据
      await fetchData();
    } else if (editingItem.value.key === 'activity') {
      // 处理活动相关操作
      if (result.mode === 'add') {
        await createActivity(props.id, result.data);
        message.success('活动记录添加成功');
      } else if (result.mode === 'edit') {
        await updateActivity(props.id, result.data.activityId, result.data);
        message.success('活动记录更新成功');
      }
      // 重新获取数据
      await fetchData();
    }
    
    isDrawerActive.value = false;
    emit('data-updated');
  } catch (error) {
    console.error('保存失败:', error);
    message.error('保存失败，请重试');
  } finally {
    isSaving.value = false;
  }
};

// 处理删除党支部
const handleDeleteBranch = () => {
  dialog.warning({
    title: '确认删除',
    content: '您确定要删除这个党支部吗？此操作不可恢复。',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        message.loading('正在删除党支部...', { duration: 0 });
        const result = await deleteBranch(props.id);
        
        if (result && (result.success || result)) {
          message.success('党支部删除成功！');
          setTimeout(goBackToList, 1500);
        } else {
          message.error('删除失败，请重试');
        }
      } catch (error) {
        console.error('删除党支部失败:', error);
        message.error('删除党支部失败，请重试');
      }
    }
  });
};

// 处理编辑操作
const handleCommitteeEditHistorical = (item, data) => {
  openDrawer(item, 'edit', data);
};

const handleActivityEdit = (item, data) => {
  openDrawer(item, 'edit', data);
};

// 处理删除操作
const handleDelete = (type, data) => {
  dialog.warning({
    title: `确认删除${type === 'committee' ? '支委信息' : '活动记录'}`,
    content: '您确定要删除这条记录吗？此操作不可恢复。',
    positiveText: '确认删除',
    negativeText: '取消',
    onPositiveClick: async () => {
      try {
        message.loading(`正在删除${type === 'committee' ? '支委信息' : '活动记录'}...`, { duration: 0 });
        
        // 模拟删除操作 - 从本地数据中删除
        if (branch.value) {
          if (type === 'committee') {
            const index = branch.value.branchCommittees?.findIndex(c => c.committeeId === data.committeeId);
            if (index !== -1) {
              branch.value.branchCommittees.splice(index, 1);
            }
          } else if (type === 'activity') {
            const index = branch.value.branchActivities?.findIndex(a => a.activityId === data.activityId);
            if (index !== -1) {
              branch.value.branchActivities.splice(index, 1);
            }
          }
        }
        
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 500));
        
        message.success(`${type === 'committee' ? '支委信息' : '活动记录'}删除成功！`);
        emit('data-updated');
      } catch (error) {
        console.error(`删除${type === 'committee' ? '支委信息' : '活动记录'}失败:`, error);
        message.error(`删除${type === 'committee' ? '支委信息' : '活动记录'}失败，请重试`);
      }
    }
  });
};

// 【修改点 9】: 使用生命周期钩子来触发数据获取
onMounted(() => {
  fetchData();
});

// 监听路由 id 的变化，以便在 /branches/1 和 /branches/2 之间切换时能重新加载数据
watch(() => props.id, (newId, oldId) => {
  if (newId !== oldId) {
    fetchData();
  }
});
</script>